package com.feilo.util;

import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONObject;


public class BaseUtil {

	public static String getReturnData(String urlString) {
		String res = "";
		try {
			URL url = new URL(urlString);
			java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			java.io.BufferedReader in = new java.io.BufferedReader(
					new java.io.InputStreamReader(conn.getInputStream(),"UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				res += line + "\n";
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}

	
	public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }
	
	public static String merge(String soure1,String soure2){
		String ret = null  ;

		return ret ;
	}
	
	public static void replaceImeiFile(String account,String pwd,String imei){
		String filePath = BaseUtil.class.getClass().getResource("/").getPath()+"imei.json";
		String str = BaseUtil.replaceBlank(TextFileUtil.read(filePath));
		String[] imeis = imei.split(",");
		StringBuffer imeiTemp = new StringBuffer() ;
		String jimei = "" ;
		//判断account是否在字符串中
		int index = str.indexOf(account);
		if(index>=0){
			//把页面获取的imei加入用户所对应的imei
			//取出json串中的imei数组
			JSONObject jsonObject = new JSONObject(str);
			JSONArray data =jsonObject.getJSONArray("data");
			for (int i = 0; i < data.length(); i++) {
				JSONObject jo = data.getJSONObject(i);
				if(jo.get("account").toString().equals(account)){
					jimei = jo.get("imei").toString();
					imeiTemp.append(jimei);
					break ;
				}
			}
			for(String s : imeis){
				if(!jimei.contains(s)){
					imeiTemp.append(",").append(s);
				}
			}
			str = str.replaceAll(jimei, imeiTemp.toString());
		}else{
			String son = ",{\"account\":\""+account+"\"," + "\"pwd\":\""+pwd+"\"," + "\"imei\":\""+imei+"\"}]}" ;
			str = str.substring(0,str.length()-2)+son;
		}
		
		TextFileUtil.write(filePath, false, str);	
	}

}
